package top.zy.admin.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.zy.admin.dto.AdminInfo;
import top.zy.admin.entity.Admin;
import top.zy.admin.service.AdminAuthService;
import top.zy.admin.vo.AdminInfoVo;
import top.zy.admin.vo.AdminPermissionInfo;
import top.zy.common.zymallcommon.utils.resp.ApiResponse;
import top.zy.common.zymallcommon.utils.resp.ApiResponseStatus;
import top.zy.common.zymallcommon.utils.resp.ResponseUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 10:54 2019/7/18
 */
@RestController
@RequestMapping("auth")
public class AdminAuthController {

      @Autowired
      @Qualifier("adminAuthServiceImpl")
      private AdminAuthService adminAuthService;

    /***
     * 登录
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public ApiResponse login(@RequestBody Admin admin, HttpServletRequest request){
      if (StringUtils.isEmpty(admin.getUsername())||StringUtils.isEmpty(admin.getPassword())){
        ResponseUtil.badArgument();
      }
        Subject currentUserSubject = SecurityUtils.getSubject();
        try {
            currentUserSubject.login(new UsernamePasswordToken(admin.getUsername(),admin.getPassword()));
        }catch (UnknownAccountException e){
            return ResponseUtil.fail(ApiResponseStatus.ADMIN_USERNAME_PASSWORD_FAIL);
        } catch (AuthenticationException e) {
               return ResponseUtil.fail(ApiResponseStatus.ADMIN_INVALID_ACCOUNT);
        }
        AdminInfoVo adminInfoVo=adminAuthService.login(request);
        return ResponseUtil.ok(adminInfoVo);
    }

    @PostMapping("info")
    public ApiResponse info(){
       AdminPermissionInfo adminPermissionInfo=adminAuthService.getAdminPermissionInfo();
      return ResponseUtil.ok(adminPermissionInfo);
    }

    @GetMapping("/401")
    public ApiResponse unLogin(){
        return ResponseUtil.unlogin();
    }
    @GetMapping("/403")
    public ApiResponse unAuth(){
        return ResponseUtil.unauthz();
    }
}
